package com.studynotes.dev.tech.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.studynotes.dev.tech.aspect.datasource.DynamicDataSource;
import com.studynotes.dev.tech.config.properties.DynamicDataSourceFactory;
import com.studynotes.dev.tech.config.properties.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

/**
 * @author Liu XiaoJun
 * @description: TODO
 * @date 2025-11-07 17:19:42
 */
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig {

    @Autowired
    private DynamicDataSourceProperties properties;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DruidDataSource defaultDataSource(DataSourceProperties dataSourceProperties) {
        //默认数据源,通过配置获取创建

        return DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
    }

    @Bean
    @Primary
    @DependsOn({"defaultDataSource"})
    public DynamicDataSource dynamicDataSource(DruidDataSource defaultDataSource) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //设置targetDataSources(通过数据库配置获取，首次创建没有数据源)
        dynamicDataSource.setTargetDataSources(DynamicDataSource.targetDataSources);

        //默认数据源
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
        return dynamicDataSource;
    }

}
